package com.books.controller;

import com.books.constant.Constants;
import com.books.enums.BookStatusEnum;
import com.books.enums.ResultCodeEnum;
import com.books.model.*;
import com.books.service.BookService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/book")
@RestController
@Slf4j
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/addBook",produces = "application/json")
    public String addBook(BookInfo bookInfo){
        log.info("添加图书");
return bookService.addBook(bookInfo);
    }
    @RequestMapping("/getListByPage")
    public Result<ResponseResult<BookInfo>>getListByPage(PageRequest pageRequest, HttpSession session){
        if(session.getAttribute(Constants.SESSION_USER_KEY)==null){
            return Result.unlogin("用户未登录");
        }
        UserInfo userInfo=(UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        if(userInfo==null||userInfo.getId()<=0){
          Result.unlogin("用户未登录");
            //用户未登录
        }
            //用户登录
        ResponseResult<BookInfo>listByPage=bookService.getListByPage(pageRequest);
        return Result.success(listByPage);
    }
    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId){
        log.info("查询图书信息，bookId:"+bookId);
        return bookService.queryBookById(bookId);
    }

    @RequestMapping(value = "/updateBook")
public Result updateBook(BookInfo bookInfo){
        log.info("修改图书,bookInfo:{}",bookInfo);
    try{
bookService.updateBook(bookInfo);
        log.info("修改图书成功");
        return Result.success("");
    }catch (Exception e){

        log.error("修改图书发生异常,e:{}",e);
        return Result.fail("修改图书发生异常");
    }
    }

    @RequestMapping(value = "/deleteBook")
    public Result deleteBook(Integer id){
        try{
            BookInfo bookInfo=queryBookById(id);
            log.info("删除图书,bookInfo:{}"+bookInfo);
            bookInfo.setId(id);
            bookInfo.setStatus(BookStatusEnum.DELETE.getCode());
            bookService.updateBook(bookInfo);
            log.info("删除图书成功");
            return Result.success("");
        }catch (Exception e){

            log.error("删除图书发生异常,e:{}",e);
            return Result.fail("删除图书发生异常");
        }
    }

    @RequestMapping("/batchDelete")
    public Boolean batchDelete(@RequestParam List<Integer>ids){
 return bookService.batchDelete(ids);
    }


}
